Page({
  data: {
    courseId: null,
    course: null,
    orderNo: '',
    orderTime: '',
    discount: 0
  },

  onLoad(options) {
    if (options.id) {
      this.setData({
        courseId: options.id
      })
      this.loadCourseInfo()
      this.generateOrder()
    } else {
      wx.showToast({
        title: '参数错误',
        icon: 'error',
        success: () => {
          setTimeout(() => {
            wx.navigateBack()
          }, 1500)
        }
      })
    }
  },

  // 加载课程信息
  loadCourseInfo() {
    // 模拟API调用
    setTimeout(() => {
      const courseDetail = {
        id: this.data.courseId,
        title: 'Vue.js 3.0 从入门到精通',
        description: '从基础到实战，全面掌握Vue3新特性和开发技巧',
        coverUrl: '/assets/images/course/vue3.png',
        teacherName: '张老师',
        price: 299,
        originalPrice: 399
      }
      
      this.setData({
        course: courseDetail,
        discount: courseDetail.originalPrice - courseDetail.price
      })
    }, 500)
  },

  // 生成订单
  generateOrder() {
    // 生成订单号
    const now = new Date()
    const orderNo = 'ORDER' + now.getFullYear() + 
                   this.padZero(now.getMonth() + 1) + 
                   this.padZero(now.getDate()) + 
                   this.padZero(now.getHours()) + 
                   this.padZero(now.getMinutes()) + 
                   this.padZero(now.getSeconds()) + 
                   Math.floor(Math.random() * 1000).toString().padStart(3, '0')
    
    // 格式化订单时间
    const orderTime = `${now.getFullYear()}-${this.padZero(now.getMonth() + 1)}-${this.padZero(now.getDate())} ${this.padZero(now.getHours())}:${this.padZero(now.getMinutes())}:${this.padZero(now.getSeconds())}`
    
    this.setData({
      orderNo,
      orderTime
    })
  },

  // 数字补零
  padZero(num) {
    return num < 10 ? '0' + num : num
  },

  // 支付订单
  payOrder() {
    wx.showLoading({
      title: '支付处理中',
    })
    
    // 模拟调用支付接口
    setTimeout(() => {
      wx.hideLoading()
      
      // 模拟支付成功
      wx.navigateTo({
        url: `/pages/order/result?orderNo=${this.data.orderNo}&status=success`
      })
      
      // 实际开发中，这里应该调用微信支付接口
      // this.wxPay()
    }, 1500)
  },
  
  // 调用微信支付
  wxPay() {
    // 实际开发中，需要先调用后端接口获取支付参数
    wx.request({
      url: 'https://api.example.com/pay/create',
      method: 'POST',
      data: {
        courseId: this.data.courseId,
        orderNo: this.data.orderNo
      },
      success: (res) => {
        if (res.data.code === 0) {
          const payParams = res.data.data
          
          // 调用微信支付
          wx.requestPayment({
            timeStamp: payParams.timeStamp,
            nonceStr: payParams.nonceStr,
            package: payParams.package,
            signType: payParams.signType,
            paySign: payParams.paySign,
            success: () => {
              // 支付成功
              wx.navigateTo({
                url: `/pages/order/result?orderNo=${this.data.orderNo}&status=success`
              })
            },
            fail: (err) => {
              console.log('支付失败', err)
              if (err.errMsg !== 'requestPayment:fail cancel') {
                wx.navigateTo({
                  url: `/pages/order/result?orderNo=${this.data.orderNo}&status=fail`
                })
              }
            }
          })
        } else {
          wx.showToast({
            title: res.data.message || '支付失败',
            icon: 'none'
          })
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        })
      },
      complete: () => {
        wx.hideLoading()
      }
    })
  }
})